package com.ming.ultlight

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.pm.PackageManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.RecyclerView

class DevicesAdapter(context: Context):BaseAdapter() {

    private var devicesList: MutableList<BluetoothDevice> = mutableListOf()
    private var mContext :Context = context

    @SuppressLint("MissingPermission")
    fun addDevice(device: BluetoothDevice){
        if(device.name == null){
            return
        }
        if(devicesList.contains(device)){
            return
        }
        devicesList.add(device)
    }

    override fun getCount(): Int {
        return devicesList.size
    }

    override fun getItem(idx: Int): Any {
        return devicesList[idx]
    }

    override fun getItemId(idx: Int): Long {
        return idx.toLong()
    }

    @SuppressLint("MissingPermission")
    override fun getView(position: Int, view: View?, viewGroup: ViewGroup?): View {
        var devViewHolder :DeviceViewHolder
        var convertView = view
        if(convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.lv_item_device, null)
            devViewHolder = DeviceViewHolder(convertView)
            convertView.tag = devViewHolder
        }else{
            devViewHolder = convertView.tag as DeviceViewHolder
        }
        devViewHolder.deviceIcon.setImageResource(R.drawable.ic_bluetooth)
        devViewHolder.deviceName.text = devicesList[position].name

        return convertView!!
    }

}

private class DeviceViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
    var deviceIcon:ImageView = itemView.findViewById(R.id.item_img)
    var deviceName:TextView = itemView.findViewById(R.id.item_service_uuid)
}